﻿#include "FindFundDialog.h"
#include"FindFundNameThread.h"
#include"FindFund.h"
#include"FuncEvent.h"
#include"MainWindow.h"
#include"FindHistoryDockWidget.h"
#include"FundInfoDockWidget.h"
#include<QLineEdit>
#include<QMessageBox>
#include<QCompleter>
#include<QDebug>
FindFundDialog::FindFundDialog(FindFund* FindFund,const QString& name, QWidget* parent)
	:EditDialog(name,parent),
    m_FindFund(FindFund)
{
    installEventFilter(new FuncEventFilter(this));
}

void FindFundDialog::init()
{
	m_Edit->setMaxLength(6);
	setIntValidator(1, 999999);
     setCompleter();
    connect(m_Edit, &QLineEdit::textChanged, [=](const QString& str) {
        auto info = m_FindFund->FundForm()[str.toInt()].name;
        if (info.isEmpty())
            setWindowTitle("没有这个基金");
        else
            setWindowTitle(info);
        });
    connect(m_Edit, &QLineEdit::returnPressed, [=]() {
        int codeNum = text().toInt();
        auto info = m_FindFund->FundForm();
        if (info.find(codeNum)== info.end())
        {
            //m_FindFund->FundForm().erase(m_FindFund->FundForm().find(codeNum));
            info[codeNum].name = m_FindFund->FindName(codeNum);
        }
        if (info[codeNum].name.isEmpty())
        {
            QMessageBox::information(this, "温馨提示", "没有这个基金！！！");
        }
        else 
        {
                done(codeNum);
        }
        //qInfo() << "回车"; 
        });
}

void FindFundDialog::setCompleter()
{
   static auto func=[this]()->bool {
        QStringList strList;
        for (auto& data : m_FindFund->FundForm())
        {
            strList.push_back(data.second.code);
        }
        auto Completer = new QCompleter(strList, this);
        this->edit()->setCompleter(Completer);

        //基金信息FundInfoDockWidget窗口按钮启用
        auto FindHistoryDock = static_cast<FindHistoryDockWidget*>(parent());
        auto MianWindow = static_cast<MainWindow*>(FindHistoryDock->parent());
        MianWindow->FundInfoDock()->init();
        sendMessage("自动补全已设置完毕", 5000);
        return true;
    };
   
    if (m_FindFund->FundForm().empty())
    {
        sendMessage("获取数据中");
        findThread = new FindFundNameThread(this);
        findThread->FindFundName(m_FindFund);
        connect(findThread, &FindFundNameThread::ret, [=](int val) {
            QString str = QString("获取到%1条数据，正在设置自动补全模式").arg(val);
        sendMessage(str, 5000);
        new FuncEvent(parent(), func);
            });
        findThread->start();
    }
    else
    {
        sendMessage("开始设置自动补全功能", 5000);
        new FuncEvent(parent(),func);
    }
}


